package com.chinawayltd.ews.sample.core.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.consts.SystemConsts;
import com.chinawayltd.ews.sample.manager.openApi.OpenApiManager;
import com.chinawayltd.ews.sample.manager.redis.TokenCacheManager;
import com.chinawayltd.ews.sample.model.openApi.UserDTO;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: greeProject
 * @description:
 * @author: xiazj
 * @create: 2018-05-16 19:44
 **/
public class WebTokenInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String HEADER_TOKEN = "token";

    @Autowired
    private TokenCacheManager tokenCacheManager;
    @Autowired
    private OpenApiManager openApiManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token = request.getHeader(HEADER_TOKEN);
        if(StringUtils.isNotBlank(token)){
            //先去redis找token有没有对应的缓存信息
            UserDTO user = tokenCacheManager.getUserByToken(token);
            //redis找不到就去请求G7的用户中心去拿，并放到redis中
            if(user == null){
                user = openApiManager.getUserByToken(token);
                
                if("777".equals(token)){
                    user = new UserDTO();
                    user.setUsername("zhangsan");
                    user.setRealname("张三");
                }

                if(user != null)tokenCacheManager.setTokenUser(token, user);
            }

            if(user != null){
                request.setAttribute(SystemConsts.SESSION_USER, user);
                return true;
            }
        }

        ResultModel model = new ResultModel();
        model.setCode(ResultModel.CODE_TOKEN_INVALID);
        model.setMsg("Invalid token!");
        sendJSON(model, response);
        return false;
    }

    private void sendJSON(ResultModel model, HttpServletResponse response){
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(model));
        } catch (Exception e) {
            logger.error("发送JSON数据出错：", e);
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
